﻿using System.Windows;
using System.Windows.Controls;
using System;
using System.Windows.Input;

namespace LinkED_WP
{
    public partial class LinkED_POP_SET : UserControl
    {
        public LinkED_POP_SET()
        {
            InitializeComponent();
            SetInputScope(txtPort);
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            UInt32 port = Convert.ToUInt32(txtPort.Text);

            string strType = LPType.SelectedItem as string;

            if (port >= 10000 && port <= 20000 && strType != string.Empty)
            {
                LinkED_DataSource.SetCfgParameters(Convert.ToUInt16(port), strType);

                this.CloseMeAsPopup();
            }
            else
            {
                MessageBox.Show("端口必须在10000～20000之间的整数");
            }

        }

        private void CancleButton_Click(object sender, RoutedEventArgs e)
        {

            this.CloseMeAsPopup();
        }

        private void SetInputScope(TextBox txtBox)
        {
            InputScopeNameValue digitalInput = InputScopeNameValue.TelephoneNumber;
            txtBox.InputScope = new InputScope()
            {
                Names = { new InputScopeName() { NameValue = digitalInput } }
            };
        }

        private void txtPort_KeyUp(object sender, KeyEventArgs e)
        {
            MaskNumericInput((TextBox)sender, false);
        }

        private void MaskNumericInput(TextBox textBoxControl, bool allowDecimals)
        {
            string[] invalidChars = { "*", "#", ".", "(", ")", "x", "-", "+", " ", "@"};

            if(!allowDecimals)
            {
                invalidChars[invalidChars.Length - 1] = ",";
            }

            foreach (string s in invalidChars)
            {
                textBoxControl.Text = textBoxControl.Text.Replace(s, "");
            }

            int firstDotIndex = textBoxControl.Text.IndexOf(',');
            int lastDotIndex = textBoxControl.Text.LastIndexOf(',');

            if (firstDotIndex != lastDotIndex)
            {
                textBoxControl.Text = textBoxControl.Text.Remove(lastDotIndex);
            }

            textBoxControl.SelectionStart = textBoxControl.Text.Length;

        }

    }
}
